package com.bank.manage.service.Impl;

import com.bank.manage.constance.BankConstance;
import com.bank.manage.enumerate.BankRedisKey;
import com.bank.manage.enumerate.BankStatus;
import com.bank.manage.model.vo.BaseResultKeyVO;
import com.bank.manage.service.CommonService;
import com.bank.manage.utils.Rsa2Utils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.gavin.core.attribute.AppEncryptConfig;
import org.gavin.core.enums.CommonStatus;
import org.gavin.core.exception.ParamException;
import org.gavin.core.exception.SafetyException;
import org.redis.service.RedisService;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * OssUploadServiceImpl
 *
 * @author grl
 * @date 2024/5/6
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CommonServiceImpl implements CommonService {

    private final RedisService redisService;
    private final AppEncryptConfig appEncryptConfig;

    @Override
    public BaseResultKeyVO getKeyPair(String random){
        BaseResultKeyVO baseResultKeyVO = new BaseResultKeyVO();
        BaseResultKeyVO clientKey = new BaseResultKeyVO();
        BaseResultKeyVO serverKey = new BaseResultKeyVO();
        try {
            // 前端加密，后端解密
            Map<String, String> mapClient = Rsa2Utils.getRsaKeyValue();
            clientKey.setClientPubKey(mapClient.get("publicKey"));
            clientKey.setClientPriKey(mapClient.get("privateKey"));

            // 后端加密，前端解密
            Map<String, String> mapServer = Rsa2Utils.getRsaKeyValue();
            serverKey.setClientPubKey(mapServer.get("publicKey"));
            serverKey.setClientPriKey(mapServer.get("privateKey"));

            // 前端加密公钥
            baseResultKeyVO.setClientPubKey(mapClient.get("publicKey"));
            // 前端加密私钥
            baseResultKeyVO.setClientPriKey(mapServer.get("privateKey"));
        } catch (NoSuchAlgorithmException e) {
            log.error("获取秘钥失败");
            throw SafetyException.le(BankStatus.GET_SK_FAIL, BankConstance.MODEL_NAME,random);
        }
        BankRedisKey apiAccessRsaFirst = BankRedisKey.API_ACCESS_RSA_FIRST;
        apiAccessRsaFirst.set(random, appEncryptConfig.getSessionTimeout(),clientKey.getClientPriKey());
        BankRedisKey apiAccessRsaSecond = BankRedisKey.API_ACCESS_RSA_SECOND;
        apiAccessRsaSecond.set(random,appEncryptConfig.getSessionTimeout(),serverKey.getClientPubKey());
        if(!redisService.ifAbsent(apiAccessRsaFirst)){
           throw ParamException.le(BankStatus.UNIQUE_VALUE_MULTIPLE_USES);
        }
        redisService.add(apiAccessRsaSecond);
        return baseResultKeyVO;
    }

}
